package com.sky.product.controller;

import com.sky.api.domain.entity.Dish;
import com.sky.common.result.PageResult;
import com.sky.common.result.Result;

import com.sky.product.domain.dto.DishDTO;
import com.sky.product.domain.dto.DishPageQueryDTO;
import com.sky.api.domain.vo.DishVO;
import com.sky.product.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
@Slf4j
public class AdminDishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDTO 菜品信息
     */
    @PostMapping
    @ApiOperation("新增菜品")
    @CacheEvict(cacheNames = "dishDTOCache", key = "#dishDTO.categoryId")   // 管理端新增菜品时要删除旧缓存,更新缓存,保证显示的是最新的菜品数据
    public Result save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品: {}", dishDTO);
        dishService.saveWithFlavor(dishDTO);

        // 修改成功后, 精准匹配清理缓存
//        final String key = "dish_" + dishDTO.getCategoryId();
//        clearCache(key);
        return Result.success();
    }

    /**
     * 分页查询菜品
     *
     * @param dishPageQueryDTO 菜品分页查询条件
     */
    @GetMapping("/page")
    @ApiOperation("分页查询菜品")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("分页查询菜品: {}", dishPageQueryDTO);
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 批量删除菜品
     *
     * @param ids 菜品id
     */
    @DeleteMapping
    @ApiOperation("批量删除菜品")
    @CacheEvict(cacheNames = "dishCache", allEntries = true)
    public Result delete(@RequestParam List<Long> ids) { // 前端传来的是形式较特殊的字符串"1,2,3",需要转换为List<Long>,故用@RequestParam使MVC框架自动转换以接收
        log.info("批量删除菜品: {}", ids);
        dishService.deleteBatch(ids);

        // 把所有菜品缓存清理掉,即所有dish_开头的key
//        clearCache("dish_*");

        return Result.success();
    }

    /**
     * 根据id查询菜品
     *
     * @param id 菜品id
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public Result<DishVO> getById(@PathVariable Long id) {
        log.info("根据id查询菜品: {}", id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }

    /**
     * 修改菜品
     *
     * @param dishDTO 菜品信息
     */
    @PutMapping
    @ApiOperation("修改菜品")
    @CacheEvict(cacheNames = "dishDTOCache", allEntries = true)
    public Result update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品: {}", dishDTO);
        dishService.updateWithFlavor(dishDTO);

        // 把所有菜品缓存清理掉,即所有dish_开头的key
//        clearCache("dish_*");

        return Result.success();
    }

    /**
     * 菜品起售停售
     *
     * @param status 起售状态：0-停售，1-起售
     * @param id     菜品id
     * @return 成功或失败提示信息
     */
    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售停售")
    @CacheEvict(cacheNames = "dishCache", allEntries = true)
    public Result<String> startOrStop(@PathVariable Integer status, Long id) {
        log.info("菜品起售停售: id={}, status={}", id, status);
        dishService.startOrStop(status, id);

        // 把所有菜品缓存清理掉,即所有dish_开头的key
//        clearCache("dish_*");

        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId 分类id
     * @return 菜品列表
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId) {
        log.info("根据分类id查询菜品: categoryId={}", categoryId);
        return Result.success(dishService.list(categoryId));
    }

    /**
     * 根据模式清除缓存数据,只在本类中使用,不对外暴露,故用private修饰
//     * @param pattern 模式
     */
//    private void clearCache(String pattern) {
//        final Set keys = redisTemplate.keys(pattern);
//        redisTemplate.delete(keys);
//    }

    @GetMapping("/count")
    @ApiOperation("根据条件统计菜品数量")
    public Result<Integer> countByMap(@RequestParam("status") Integer status){
        HashMap<Object, Object> map = new HashMap<>();
        map.put("status", status);
        return Result.success(dishService.countByMap(map));
    }

}






















